package com.app.ar;

import java.util.ArrayList;
import com.app.campusguide.Class_view;
import com.app.campusguide.R;
import com.app.location.MyLocationListener;
import com.app.sqlite_connect.HandlerSqlite;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.SensorListener;
import android.hardware.SensorManager;
import android.hardware.Camera.ShutterCallback;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

@SuppressWarnings("deprecation")
public class AR_Ubication_Site extends Activity implements SurfaceHolder.Callback, SensorListener{
	private final String APP_LOG = "AR_Ubication_Site";
	static final int sensor = SensorManager.SENSOR_ORIENTATION; 
	private final double dRadiusEarth = 6371F;
	
	private SensorManager sensorManager; 
	private LayoutInflater myInflater = null;
	private Camera myCamera;
	boolean myPreviewRunning = false;
	private SurfaceHolder mySurfaceHolder;
	private SurfaceView mySurfaceView;
	private HandlerSqlite database;
	private LocationManager mLocationManager;
	private Location loc_current_location;
	private MyLocationListener mLocationListener;
	private ProgressDialog pd;
	
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        database = new HandlerSqlite(this);
        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.camera_activity);
        mySurfaceView = (SurfaceView) findViewById(R.id.surface);
        mySurfaceHolder = mySurfaceView.getHolder();
        mySurfaceHolder.addCallback(this);
        myInflater = LayoutInflater.from(this);
        
        View overView = myInflater.inflate(R.layout.activity_explore,null);
        this.addContentView(overView, new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        
        setDataView();
    }
	
	ShutterCallback myShutterCallback = new ShutterCallback() {
    	@Override
    	public void onShutter() {
    	}
    };
    
	@Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    	// TODO Auto-generated method stub
    	try{
    		if(myPreviewRunning){
    			myCamera.stopPreview();
    			myPreviewRunning = false;
    		}
    		Camera.Parameters p = myCamera.getParameters();
    		p.setPreviewSize(width,height);
    		myCamera.setParameters(p);
    		myCamera.setPreviewDisplay(holder);
    		myCamera.startPreview();
    		myPreviewRunning = true;
    	}catch(Exception e){}
    }
	
	@Override
	public void surfaceCreated(SurfaceHolder holder) {
 	// TODO Auto-generated method stub
		myCamera = Camera.open();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		myCamera.stopPreview();
		myPreviewRunning = false;
		myCamera.release();
		myCamera = null;
    }
	
	/**
	 * This method setup values of different labels on surface view
	 */
	@SuppressLint("NewApi")
	private void setDataView(){
		//Query for class to take now
		ArrayList<Class_view> classes_to_take = database.queryNextClassView();
		TextView txtv_class_name = (TextView) findViewById(R.id.txtv_ar_class_name);
		TextView txtv_time = (TextView) findViewById(R.id.txtv_ar_time);
		TextView txtv_classroom_name = (TextView) findViewById(R.id.txtv_ar_classroom_name);
		TextView txtv_distance_to = (TextView) findViewById(R.id.txtv_ar_distance_to);
		TextView txtv_orientation = (TextView) findViewById(R.id.txtv_ar_found_orientation);
		TextView txtv_level = (TextView) findViewById(R.id.txtv_ar_classroom_level);
		
		txtv_class_name.setBackgroundColor(Color.WHITE);
		txtv_class_name.setAlpha(0.5F);
		txtv_time.setBackgroundColor(Color.WHITE);
		txtv_time.setAlpha(0.5F);
		txtv_classroom_name.setBackgroundColor(Color.WHITE);
		txtv_classroom_name.setAlpha(0.5F);
		txtv_distance_to.setBackgroundColor(Color.WHITE);
		txtv_distance_to.setAlpha(0.5F);
		txtv_orientation.setBackgroundColor(Color.WHITE);
		txtv_orientation.setAlpha(0.5F);
		txtv_level.setBackgroundColor(Color.WHITE);
		txtv_level.setAlpha(0.5F);
		
		ImageView im_logo = (ImageView) findViewById(R.id.img_view_ar_logo);
        im_logo.setAlpha(127);
		
		if(classes_to_take.size() != 0){
			txtv_class_name.setText(R.string.str_your_class);
			txtv_class_name.setText(txtv_class_name.getText()+" "+classes_to_take.get(0).getStr_class_name());
			txtv_time.setText(R.string.str_class_start_at);
			txtv_time.setText(txtv_time.getText()+" "+classes_to_take.get(0).getStr_start_hour());
			TextView txtv_tmp = new TextView(getApplicationContext());
			txtv_tmp.setText(R.string.str_class_end_at);
			txtv_time.setText(txtv_time.getText()+" "+txtv_tmp.getText());
			txtv_time.setText(txtv_time.getText()+" "+classes_to_take.get(0).getStr_end_hour());
			txtv_classroom_name.setText(R.string.str_at_classroom);
			txtv_classroom_name.setText(txtv_classroom_name.getText()+" "+classes_to_take.get(0).getStr_site_name());
			if(!(classes_to_take.get(0).getStr_site_latitude().equals("N/A")))
			{
				writeSignalGPS();
			}
			
		}else{
			txtv_class_name.setText(R.string.str_not_classes_found);
		}
	}
    
	/**
	 * Informs the view of the search start signal and start the process
	 */
    private void writeSignalGPS() {
    	DialogInterface.OnCancelListener dialogCancel = new DialogInterface.OnCancelListener() {
            public void onCancel(DialogInterface dialog) {
                Toast.makeText(getBaseContext(), getResources().getString(R.string.gps_signal_not_found), Toast.LENGTH_SHORT).show();
            }
        };
		pd = ProgressDialog.show(this, this.getResources().getString(R.string.search), this.getResources().getString(R.string.search_signal_gps), true, true, dialogCancel);
		lookup();
    }

    /**
     * Indicates the sensor begins with the search
     */
	public void lookup() {
		TextView txtv_distance_to = (TextView) findViewById(R.id.txtv_ar_distance_to);
		TextView txtv_level = (TextView) findViewById(R.id.txtv_ar_classroom_level);
		mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			mLocationListener = new MyLocationListener(this,pd,loc_current_location,txtv_distance_to,txtv_level);
			mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
		} else {
            Toast.makeText(getBaseContext(), getResources().getString(R.string.gps_signal_not_found), Toast.LENGTH_SHORT).show();
		}
	}
	
	/**
	 * This method manage orientation of device Vs orientation of site based on earth coordinates
	 */
	public void onSensorChanged(int sensor, float[] values) { 
		TextView tv = (TextView)findViewById(R.id.txtv_ar_found_orientation);
		ArrayList<Class_view> classes_to_take = database.queryNextClassView();
		if(classes_to_take.size() != 0)
		{
			Location loc_classroom = new Location(LocationManager.GPS_PROVIDER);
			loc_classroom.setLatitude(Double.valueOf(classes_to_take.get(0).getStr_site_latitude()));
	        loc_classroom.setLongitude(Double.valueOf(classes_to_take.get(0).getStr_site_longitude()));

			double dCoordX = 0.0F;
			double dCoordY = 0.0F;
			
			double dLatitude = loc_classroom.getLatitude();
			double dLongitude = loc_classroom.getLongitude();
			
			if(dLongitude < 0)
			{
				dLongitude = (180 + dLongitude) +180;
			}
			
			if(dLatitude < 0)
			{
				dLatitude = (360 - dLatitude);
			}
			
			//Calculate Cartesian coordinates
			dCoordX = (dRadiusEarth * (Math.sin(dLatitude)) * Math.cos(dLongitude));
			dCoordY = (dRadiusEarth * (Math.sin(dLatitude)) * Math.sin(dLongitude));
			//Calculate angle value base on coordinates
			double dAngleValue = Math.atan((dCoordY/dCoordX));
			
			
			//Fix angle value based on quadrant of coordinates
			if(dCoordX>0 && dCoordY>0){
				dAngleValue = 90 - dAngleValue;
			}else if(dCoordX<0 && dCoordY>0){
				dAngleValue = 270 + dAngleValue;
			}else if(dCoordX<0 && dCoordY<0){
				dAngleValue = 270 - dAngleValue;
			}else if(dCoordX>0 && dCoordY<0){
				dAngleValue = 90 + dAngleValue;
			}
			
			//Convert value angle to same system value of sensor 
			if(dAngleValue >= 0 && dAngleValue <= 90)
			{
				dAngleValue = 90 - dAngleValue;
			}else if(dAngleValue > 90 && dAngleValue <= 360)
			{
				dAngleValue = (90 - dAngleValue) + 360;
			}

			if (sensor != AR_Ubication_Site.sensor)
			{
				return;
			}
			//Sets the tag value considering a tolerance of 10 degrees with respect to the position sensor
			if(values[0] >= dAngleValue-10 && values[0] <= dAngleValue+10){
				tv.setText(R.string.str_direction_found);
				tv.setTextColor(Color.BLUE);
			}else
			{
				tv.setText(R.string.str_finding_direction);
				tv.setTextColor(Color.GREEN);
			}
		}
        
	}
	
	public void onAccuracyChanged(int sensor, int accuracy) { 
	}
	
	public void onStop(){
		super.onStop();
		try{
			mLocationManager.removeUpdates(mLocationListener);}
		catch(Exception e){};
	}
	
	public void onPause(){
		super.onPause();
		try{
		mLocationManager.removeUpdates(mLocationListener);}
		catch(Exception e){};
		sensorManager.unregisterListener(this);
	}
	
	@Override 
	public void onResume() { 
		super.onResume(); 
		sensorManager.registerListener((SensorListener) this, sensor); 
	}
}